package com.cskaoyan.config;

import com.cskaoyan.realm.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author: lds
 * @clsss: CustomAuthenticator
 */
/*用认证器进行分配*/

public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        //原始realm
        Collection<Realm> orginRealms = this.getRealms();
        //对realm进行分发
        //通过token携带类型信息
        MallToken token = (MallToken) authenticationToken;
        String type = token.getType();
        //接下来要使用的realm
        ArrayList<Realm> realms = new ArrayList<>();
        for (Realm orginRealm : orginRealms) {
            //AdminRealm 变成小写 adminrealm 传进来的类型 admin/wx
            if (orginRealm.getName().toLowerCase().contains(type)){
                realms.add(orginRealm);
            }

        }

        return realms.size() == 1 ? this.doSingleRealmAuthentication((Realm)realms.iterator().next(), authenticationToken) : this.doMultiRealmAuthentication(realms, authenticationToken);

    }
}
